package com.spzx.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.spzx.cart.api.RemoteCartService;
import com.spzx.cart.api.domain.CartInfo;
import com.spzx.common.core.constant.SecurityConstants;
import com.spzx.common.core.context.SecurityContextHolder;
import com.spzx.common.core.domain.R;
import com.spzx.common.core.exception.ServiceException;
import com.spzx.common.core.utils.StringUtils;
import com.spzx.common.core.utils.bean.BeanUtils;
import com.spzx.common.core.utils.uuid.UUID;
import com.spzx.common.security.utils.SecurityUtils;
import com.spzx.order.domain.OrderInfo;
import com.spzx.order.domain.OrderItem;
import com.spzx.order.domain.OrderLog;
import com.spzx.order.mapper.OrderInfoMapper;
import com.spzx.order.mapper.OrderItemMapper;
import com.spzx.order.mapper.OrderLogMapper;
import com.spzx.order.query.OrderForm;
import com.spzx.order.service.IOrderInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spzx.order.vo.TradeVo;
import com.spzx.product.api.RemoteProductSkuService;
import com.spzx.product.api.RemoteSkuStockService;
import com.spzx.product.api.dto.ProductSkuVo;
import com.spzx.product.api.dto.SkuLockVo;
import com.spzx.product.api.dto.SkuPriceVo;
import com.spzx.rabbit.constant.MqConst;
import com.spzx.rabbit.service.RabbitService;
import com.spzx.user.api.RemoteUserAddressService;
import com.spzx.user.api.domain.UserAddress;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.ReactiveValueOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * <p>
 * 订单 服务实现类
 * </p>
 *
 * @author atguigu
 * @since 2025-05-09
 */
@Service
@RequiredArgsConstructor
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements IOrderInfoService {
    private final RemoteCartService remoteCartService;
    private final RedisTemplate redisTemplate;
    private final RemoteProductSkuService remoteProductSkuService;
    private final OrderLogMapper orderLogMapper;
    private final OrderItemMapper orderItemMapper;
    private final RemoteUserAddressService remoteUserAddressService;
    private final RemoteSkuStockService remoteSkuStockService;
    private final RabbitService rabbitService;
    @Override
    public TradeVo orderTradeData() {
        R<List<CartInfo>> cartCheckedList = remoteCartService.getCartCheckedList(SecurityConstants.INNER);
        if (R.FAIL == cartCheckedList.getCode()) {
            throw new ServiceException(cartCheckedList.getMsg());
        }
        List<CartInfo> cartInfoList = cartCheckedList.getData();
        TradeVo tradeVo = new TradeVo();
        //1. orderItemList
        List<OrderItem> orderItemList = cartInfoList.stream().map(cartInfo -> {
            OrderItem orderItem = new OrderItem();
            BeanUtils.copyProperties(cartInfo, orderItem);
            return orderItem;
        }).toList();
        //2. total amount
        BigDecimal totalAmount = new BigDecimal(0);
        for (OrderItem orderItem : orderItemList) {
            totalAmount = totalAmount.add(orderItem.getSkuPrice().multiply(new BigDecimal(orderItem.getSkuNum())));
        }
        //3. trade num
        String tradeNo = generateTradeNo(SecurityUtils.getUserId());
        tradeVo.setTotalAmount(totalAmount);
        tradeVo.setOrderItemList(orderItemList);
        tradeVo.setTradeNo(tradeNo);

        return tradeVo;
    }

    @Override
    public Long submitOrder(OrderForm orderForm) {
        // todo : 如何区分 立即购买与购物车结算
        //1.验证订单流水号
        //使用lua脚本解决验证并删除某个订单流水号原子性的问题
        String userTradeKey = "user:tradeNo:"+SecurityUtils.getUserId();
        // 将键的值更为 processed  表示已处理  return 1 表示处理成功
        // return -1  键存在但值不匹配，表示重复提交
        // return 0   键不存在，订单过期
        String scriptText = """
        if redis.call('get', KEYS[1]) == ARGV[1] then
            redis.call('set', KEYS[1], 'processed')
            return 1
        else
           if redis.call('exists', KEYS[1]) == 1 then
              redis.call('del',KEYS[1])
              return -1
           else
              return 0
           end
       end
       """;
        DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>();
        redisScript.setScriptText(scriptText);
        redisScript.setResultType(Long.class);
        Long flag = (Long)redisTemplate.execute(redisScript, Arrays.asList(userTradeKey), orderForm.getTradeNo());
        // 判断是否同一个表单
        if (flag == 0) {
            throw new ServiceException("操作超时，请退回重试");
        }
        if(flag == -1){
            throw new ServiceException("请勿重复提交订单");
        }

        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        //2.获得商品id列表，远程查询商品价格列表，判断是否发生变更。
        List<OrderItem> orderItemList = orderForm.getOrderItemList();
        List<Long> skuIdList = orderItemList.stream().map(OrderItem::getSkuId).collect(Collectors.toList());
        R<List<SkuPriceVo>> skuPriceListResult =remoteProductSkuService.getSkuPriceList(skuIdList, SecurityConstants.INNER);
        if(R.FAIL == skuPriceListResult.getCode()){
            throw new ServiceException(skuPriceListResult.getMsg());
        }
        List<SkuPriceVo> skuPriceList = skuPriceListResult.getData();
        Map<Long, BigDecimal> skuIdSalePriceMap = skuPriceList.stream().collect(Collectors.toMap(SkuPriceVo::getSkuId, SkuPriceVo::getSalePrice));
        String priceCheckResult = "";
        for (OrderItem orderItem : orderItemList) {
            //if有变更：远程调用，更新购物车选中商品价格，购物车获取某个商品价格，更新缓存。提示价格有变更，引导用户重新
            if(orderItem.getSkuPrice().compareTo(skuIdSalePriceMap.get(orderItem.getSkuId()))!=0){
                priceCheckResult += orderItem.getSkuName() + "\n";
            }

        }
        if(!StringUtils.isEmpty(priceCheckResult)){

            if(!orderForm.getIsBuy()){
                //更新购物车中的价格
                remoteCartService.updateCartPrice(SecurityConstants.INNER);
            }
            throw new ServiceException(priceCheckResult + "以上商品价格发生变化，请确认");
        }
        //else 没有变更
        //3.保存订单、明细、日志
        Long orderId = null;
        try {
            orderId = this.saveOrder(orderForm);
        }catch (Exception e){
            rabbitService.sendMessage(MqConst.EXCHANGE_PRODUCT, MqConst.ROUTING_UNLOCK, orderForm.getTradeNo());
            throw new ServiceException("下单失败");
        }
        //锁定库存
        List<SkuLockVo> skuLockVoList = orderItemList.stream().map(item -> {
            SkuLockVo skuLockVo = new SkuLockVo();
            skuLockVo.setSkuId(item.getSkuId());
            skuLockVo.setSkuNum(item.getSkuNum());
            return skuLockVo;
        }).collect(Collectors.toList());

        String errorMsg = remoteSkuStockService.checkAndLock(orderForm.getTradeNo(), skuLockVoList, SecurityConstants.INNER).getData();
        if(errorMsg!=null){
            throw new ServiceException(errorMsg);
        }
        //4.todo:下单

        //5 如果是购物车途径订单，删除购物车选中商品
        if(!orderForm.getIsBuy()){
            remoteCartService.deleteCartCheckedList(SecurityConstants.INNER);
        }
        // 响应订单，跳转支付

        // 订单支付倒计时  
        return orderId;
    }

    @Override
    public TradeVo buy(Long skuId) {
        R<ProductSkuVo> productSku = remoteProductSkuService.getProductSku(skuId, SecurityConstants.INNER);
        if (R.FAIL == productSku.getCode()) {
            throw new ServiceException(productSku.getMsg());
        }
        ProductSkuVo data = productSku.getData();
        OrderItem orderItem = new OrderItem();
        BeanUtils.copyProperties(data,orderItem);

        //1. orderItemList
        List<OrderItem> orderItemList = Arrays.asList(orderItem);
        //2. total amount
        //3. trade num
        String tradeNo = generateTradeNo(SecurityUtils.getUserId());
        TradeVo tradeVo = new TradeVo();
        tradeVo.setTotalAmount(data.getSalePrice());
        tradeVo.setOrderItemList(orderItemList);
        tradeVo.setTradeNo(tradeNo);
        tradeVo.setIsBuy(true);
        return tradeVo;
    }

    @Override
    public List<OrderInfo> selectUserOrderInfoList(Integer orderStatus) {
        // 获取当前登录用户的id
        Long userId = SecurityContextHolder.getUserId();
        //获取当前用户指定状态下的全部订单信息，但是每个订单明细都需要补充
        List<OrderInfo> orderInfoList = baseMapper.selectList(new LambdaQueryWrapper<OrderInfo>()
                .eq(OrderInfo::getUserId, userId)
                .eq(orderStatus != null, OrderInfo::getOrderStatus, orderStatus)
                .orderByDesc(OrderInfo::getCreateTime));

        if(!CollectionUtils.isEmpty(orderInfoList)) {
            //订单id
            List<Long> orderIdList = orderInfoList.stream().map(OrderInfo::getId).collect(Collectors.toList());

            //查询所有orderItem
            List<OrderItem> orderItemList = orderItemMapper.selectList(
                    new LambdaQueryWrapper<OrderItem>().in(OrderItem::getOrderId, orderIdList)
            );
            //映射对应订单明细
            Map<Long, List<OrderItem>> orderIdToOrderItemListMap = orderItemList.stream().collect(
                    Collectors.groupingBy(OrderItem::getOrderId)
            );
            //组装orderItemList
            orderInfoList.forEach(item -> {
                item.setOrderItemList(orderIdToOrderItemListMap.get(item.getId()));
            });
        }
        return orderInfoList;
    }

    @Override
    public OrderInfo selectOrderInfoById(Long orderId) {
        OrderInfo orderInfo = baseMapper.selectById(orderId);
        List<OrderItem> orderItems = orderItemMapper.selectList(new LambdaQueryWrapper<OrderItem>().eq(OrderItem::getOrderId, orderId));
        orderInfo.setOrderItemList(orderItems);
        return orderInfo;
    }

    @Override
    public void cancelOrder(Long orderId) {
        OrderInfo orderInfo = baseMapper.selectById(orderId);
        if(orderInfo != null && orderInfo.getOrderStatus().intValue() == 0) {//待付款
            orderInfo.setOrderStatus(-1);//已取消
            orderInfo.setCancelTime(new Date());
            orderInfo.setCancelReason("用户取消订单");
            baseMapper.updateById(orderInfo);
            //记录日志
            OrderLog orderLog = new OrderLog();
            orderLog.setOrderId(orderInfo.getId());
            orderLog.setProcessStatus(-1);
            orderLog.setNote("用户取消订单");
            orderLogMapper.insert(orderLog);

            //发送MQ消息通知商品系统解锁库存
            rabbitService.sendMessage(MqConst.EXCHANGE_PRODUCT, MqConst.ROUTING_UNLOCK, orderInfo.getOrderNo());

        }
    }

    @Override
    public OrderInfo getByOrderNo(String orderNo) {
        OrderInfo orderInfo = baseMapper.selectOne(new LambdaQueryWrapper<OrderInfo>().eq(OrderInfo::getOrderNo, orderNo));
        //订单详情
        List<OrderItem> orderItemList = orderItemMapper.selectList(
                new LambdaQueryWrapper<OrderItem>().eq(OrderItem::getOrderId, orderInfo.getId())
        );
        orderInfo.setOrderItemList(orderItemList);
        return orderInfo;
    }

    /**
     * 渲染订单确认页面-生成用户流水号
     *
     * @param userId
     * @return
     */
    private String generateTradeNo(Long userId) {
        //1.构建流水号Key
        String userTradeKey = "user:tradeNo:" + userId;
        //2.构建流水号value
        String tradeNo = UUID.randomUUID().toString().replaceAll("-", "");
        //3.将流水号存入Redis 暂存5分钟
        redisTemplate.opsForValue().set(userTradeKey, tradeNo, 5, TimeUnit.MINUTES);
        return tradeNo;
    }


    private Long saveOrder(OrderForm orderForm) {

        Long userId = SecurityContextHolder.getUserId();
        String userName = SecurityContextHolder.getUserName();

        // 保存订单记录：order_info
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setUserId(userId);
        orderInfo.setOrderNo(orderForm.getTradeNo());//订单号
        orderInfo.setNickName(userName);
        orderInfo.setRemark(orderForm.getRemark());
        orderInfo.setFeightFee(orderForm.getFeightFee());

        //远程调用获取用户地址信息
        R<UserAddress> userAddressResult = remoteUserAddressService.getUserAddress(orderForm.getUserAddressId(), SecurityConstants.INNER);
        if(R.FAIL == userAddressResult.getCode()){
            throw new ServiceException(userAddressResult.getMsg());
        }
        //获取用户地址信息
        UserAddress userAddress = userAddressResult.getData();
        //保存用户地址信息
        orderInfo.setReceiverName(userAddress.getName());
        orderInfo.setReceiverPhone(userAddress.getPhone());
        orderInfo.setReceiverTagName(userAddress.getTagName());
        orderInfo.setReceiverProvince(userAddress.getProvinceCode());
        orderInfo.setReceiverCity(userAddress.getCityCode());
        orderInfo.setReceiverDistrict(userAddress.getDistrictCode());
        orderInfo.setReceiverAddress(userAddress.getFullAddress());


        //获取订单明细表
        List<OrderItem> orderItemList = orderForm.getOrderItemList();
        //实时计算orderItem中商品的总价格
        BigDecimal totalAmount = orderItemList
                .stream()
                .map(orderItem -> orderItem.getSkuPrice().multiply(new BigDecimal(orderItem.getSkuNum())))
                .reduce(BigDecimal.ZERO, BigDecimal::add);
        //设置商品总价格
        orderInfo.setTotalAmount(totalAmount);
        orderInfo.setCouponAmount(new BigDecimal(0));//优惠券价格
        orderInfo.setOriginalTotalAmount(totalAmount);//原价
        //订单状态
        orderInfo.setOrderStatus(0);//待付款

        orderInfo.setCreateBy(userName);
        orderInfo.setUpdateBy(userName);
        baseMapper.insert(orderInfo);

        // 保存订单项记录：order_item
        for (OrderItem orderItem : orderItemList) {
            orderItem.setOrderId(orderInfo.getId());
            orderItem.setCreateBy(userName);
            orderItem.setUpdateBy(userName);
            orderItemMapper.insert(orderItem);
        }

        // 保存订单日志记录：order_log
        OrderLog orderLog = new OrderLog();
        orderLog.setOrderId(orderInfo.getId());
        orderLog.setProcessStatus(0);
        orderLog.setOperateUser(userName);
        orderLog.setNote("提交订单");
        orderLog.setCreateBy(userName);
        orderLog.setUpdateBy(userName);
        orderLogMapper.insert(orderLog);

        return orderInfo.getId();
    }
}
